package View;

import Model.User;
import factory.Constants;
import interface_.Server;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author TUAN ANH
 */
public class ServerWaiting extends javax.swing.JFrame {

    /**
     * Creates new form ServerWaiting
     */
//    boolean flagCheck = true,flagStart = true;
//    boolean startGame = false;
    User user;
    Thread requestFromClient;
    Thread requestToClient;
    Server send, receive;

    public ServerWaiting(User user) {
        this.user = user;
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception exc) {
        }
        initComponents();
        startGameButton.setEnabled(false);
        setVisible(true);
        send = new Server(Constants.PORT_SEND);
        receive = new Server(Constants.PORT_RECEIVE);
        sendDataToClient();
        receiveFromClient();
    }

    public void receiveFromClient() {
        requestFromClient = new Thread() {
            public void run() {
                try {
                    receive.initConnection();
                    while (true) {
                        String receiveData = receive.receiveData();
                        if (receiveData.equals(Constants.RECEIVE_MESSAGE_READY)) {
                            waitingClient.setText(user.getUser2() + "ready!");
                            if (readyCheckbox.isSelected()) {
                                startGameButton.setEnabled(true);
                            }
                        } else if (receiveData.equals(Constants.RECEIVE_MESSAGE_CANCEL)) {
                            waitingClient.setText("");
                            startGameButton.setEnabled(false);
                        }
                    }
                } catch (Exception ex) {
                    System.out.println(ex.toString());
                }
            }
        };
        requestFromClient.start();
    }
    private void setData(){
        idCode.setText(user.getId());
        severName.setText(user.getUser1());
        clientName.setText(user.getUser2());
        scoreOfServer.setText(String.valueOf(user.getScore1()));
        scoreOfClient.setText(String.valueOf(user.getScore2()));
    }
    public void sendDataToClient() {
        requestToClient = new Thread() {
            public void run() {
                    send.initConnection();
                    send.sentData(user.getId());
                    send.sentData(user.getUser1());
                    send.sentData(user.getUser2());
                    send.sentData(String.valueOf(user.getScore1()));
                    send.sentData(String.valueOf(user.getScore2()));
            }
        };
        requestToClient.start();
        setData();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        idLabel = new javax.swing.JLabel();
        severName = new javax.swing.JLabel();
        vs = new javax.swing.JLabel();
        clientName = new javax.swing.JLabel();
        scoreOfServer = new javax.swing.JLabel();
        scoreOfClient = new javax.swing.JLabel();
        idCode = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel8 = new javax.swing.JLabel();
        readyCheckbox = new javax.swing.JCheckBox();
        waitingServer = new javax.swing.JLabel();
        waitingClient = new javax.swing.JLabel();
        startGameButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server Waiting Room");
        setResizable(false);

        idLabel.setText("ID :");

        severName.setText("demoPlayer1");

        vs.setText("VS");

        clientName.setText("demoPlayer2");

        scoreOfServer.setText("2");

        scoreOfClient.setText("1");

        jLabel8.setText("Please select \"I'm ready\" and Press StartGame");

        readyCheckbox.setText("I'm ready");
        readyCheckbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                readyCheckboxActionPerformed(evt);
            }
        });

        waitingServer.setForeground(new java.awt.Color(0, 0, 153));

        waitingClient.setForeground(new java.awt.Color(204, 0, 0));

        startGameButton.setText("StartGame");
        startGameButton.setEnabled(false);
        startGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startGameButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(idLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(idCode, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(severName)
                        .addGap(53, 53, 53))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(100, 100, 100)
                        .addComponent(scoreOfServer, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(vs)
                        .addGap(51, 51, 51)
                        .addComponent(clientName)
                        .addGap(59, 59, 59))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(scoreOfClient, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(79, 79, 79))))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(71, 71, 71)
                        .addComponent(jLabel8))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(137, 137, 137)
                        .addComponent(readyCheckbox))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(127, 127, 127)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(waitingClient)
                            .addComponent(waitingServer)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(142, 142, 142)
                        .addComponent(startGameButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(idCode, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(idLabel)
                        .addComponent(severName)
                        .addComponent(clientName)
                        .addComponent(vs)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(scoreOfServer)
                    .addComponent(scoreOfClient))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addGap(18, 18, 18)
                .addComponent(readyCheckbox)
                .addGap(18, 18, 18)
                .addComponent(waitingServer)
                .addGap(18, 18, 18)
                .addComponent(waitingClient)
                .addGap(27, 27, 27)
                .addComponent(startGameButton)
                .addGap(40, 40, 40))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void startGameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startGameButtonActionPerformed
        // TODO add your handling code here:
        send.sentData(Constants.RECEIVE_MESSAGE_OK);
        new GameInServer(user);
        dispose();
        receive.close();
        send.close();
        requestFromClient.stop();
        requestToClient.stop();
    }//GEN-LAST:event_startGameButtonActionPerformed

    private void readyCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readyCheckboxActionPerformed
        // TODO add your handling code here: 
        if (readyCheckbox.isSelected()) {
            waitingServer.setText(user.getUser1()+ " ready ! ");
            send.sentData(Constants.RECEIVE_MESSAGE_READY);
            if (waitingClient.getText().equals(user.getUser2() + "ready!")) {
                startGameButton.setEnabled(true);
            }
        } else {
            waitingServer.setText("");
            send.sentData(Constants.RECEIVE_MESSAGE_CANCEL);
//            if (!readyCheckbox.isSelected()) {
                startGameButton.setEnabled(false);
//            }
        }
    }//GEN-LAST:event_readyCheckboxActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel clientName;
    private javax.swing.JLabel idCode;
    private javax.swing.JLabel idLabel;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JCheckBox readyCheckbox;
    private javax.swing.JLabel scoreOfClient;
    private javax.swing.JLabel scoreOfServer;
    private javax.swing.JLabel severName;
    private javax.swing.JButton startGameButton;
    private javax.swing.JLabel vs;
    private javax.swing.JLabel waitingClient;
    private javax.swing.JLabel waitingServer;
    // End of variables declaration//GEN-END:variables
}
